<template>
 <a-card 
  :bordered="false">
  <CrudTable
    ref="crudTable"
    :scroll="{ x: 2600,}"
    :bordered="true"
    :columns="columns"
    :fetchData="fetchData"
    :searchForm="searchForm"
    @rowClick="tableRowClick">

      <template #createTimeSlot="{ data, defaultValue }">
        <a-range-picker v-model="data.createTime" showTime :defaultValue="defaultValue"/>
      </template>

      <template #personnelSlot="{ data }">
        <a-select v-model="data.organization_personnel_uid" 
            placeholder="请选择" allow-clear>
          <a-option v-for="(item,index) in persionSlectList" :key="index"
          :value="item.id" :label="item.nickname" />
        </a-select>
      </template>


      <template #phoneViewedSlot="{ data }">
        <a-select  v-model="data.phone_viewed" placeholder="请选择" allow-clear>
          <a-option v-for="(item,index) in phoneViewedList" :key="index"
          :value="item.value" :label="item.label" />
        </a-select> 
      </template>

      
      <template #pushPlanSlot="{ data }">
        <a-select  v-model="data.plan" placeholder="请选择" allow-clear>
          <a-option v-for="(key,value,index) in cluePlanList" :key="index"
          :value="value" :label="key" />
        </a-select>
      </template>

      <template #mobileSearchSlot="{ data }"> 
        <a-input v-model="data.mobile" placeholder="请输入手机号" allow-clear/>
      </template>

      
      <template #mobileSlot="{ record }">
        <a-link v-if="showUserMobile(record?.id)" type="text">{{ showUserMobile(record?.id) }}</a-link>
        <a-link v-else type="text" @click="showPhone(record)">点击查看</a-link>
      </template>

      <template #genderSlot="{ record }">
          <span v-if="record.gender == 1">男</span>
          <span v-if="record.gender == 2">女</span>
      </template>

      
      <template #cellCreatetimeSlot="{ record }">
          <span>{{ compilationTime(record.createtime) }}</span>
      </template>

      <template #entryStatusSlot="{ record }">
          <span>{{ cellShowCity(record.province) }}</span>
          <span>-</span>
          <span>{{ cellShowCity(record.city) }}</span>
      </template>
      
      <template #sesameScoreSlot="{ record }">
          <span v-html="makeBetweenString(record.sesame_score)"></span>
      </template>

      <template #cellCarSlot="{ record }">
          <span v-if="record.car == 1" class="cell-warning">有</span>
          <span v-if="record.car == 0" class="cell-default">无</span>
      </template>

      <template #cellHouseSlot="{ record }">
          <span v-if="record.house == 1" class="cell-warning">有</span>
          <span v-if="record.house == 0" class="cell-default">无</span>
      </template>

      <template #accumulationFundSlot="{ record }">
          <span v-if="record.accumulation_fund == 1" class="cell-warning">有</span>
          <span v-if="record.accumulation_fund == 0" class="cell-default">无</span>
      </template>

      <template #socialSecuritySlot="{ record }">
          <span v-if="record.social_security == 1" class="cell-warning">有</span>
          <span v-if="record.social_security == 0" class="cell-default">无</span>
      </template>
      
      <template #businessOwnerSlot="{ record }">
          <span v-if="record.business_owner == 1" class="cell-warning">有</span>
          <span v-if="record.business_owner == 0" class="cell-default">无</span>
      </template>

      <template #cellPlanSlot="{ record }">
          <span>{{ cellPlanSlotConver(record.plan) }}</span>
      </template>

      <template #userInfoSlot="{ record }">
        <a-link @click="jumpToInfo(record.id)">用户详情</a-link>
      </template>  


      <template #actionSlot="{ record }">
        <a-space>
          <a-button type="primary" status="success" class="commBtn"
          @click="updatePlanPross(record)">更新沟通进度</a-button>
          <a-button type="primary" @click="onHandedOver(record)">移交</a-button>
        </a-space>
      </template>

  </CrudTable>


  <a-modal
    v-model:visible="modalVisible"
    :footer="false" title-align="start" 
    class="comomModal" :maskClosable="false">
    <template #title>
      <div class="model-title-text">移交</div>
    </template>

    <a-form ref="handOvderForm" :model="handForm" @submit="handleOverSubmit" auto-label-width>
      <a-form-item field="uid" label="原跟进经理：" 
        :rules="[{ required: true, message: '原跟进经理不能为空' }]">
        <a-input :model-value="itemNickname" disabled class="nicknameGj" style="color: #333"></a-input>
        <!-- <a-select v-model="handForm.id" placeholder="请选择" disabled allow-clear>
          <a-option v-for="(item,index) in persionSlectList" :key="index"
          :value="item.id" :label="item.nickname" />
        </a-select> -->
      </a-form-item>
      <a-form-item field="id" label="新跟进经理："
       :rules="[{ required: true, message: '新跟进经理不能为空' }]">
        <a-select v-model="handForm.uid" placeholder="请选择" allow-clear>
          <a-option v-for="(item,index) in persionSlectList" :key="index"
          :value="item.id" :label="item.nickname" />
        </a-select>
      </a-form-item>

      <a-form-item field="remark" label="移交原因：">
        <a-textarea v-model="handForm.remark" placeholder="请输入" allow-clear/>
      </a-form-item>
      <a-form-item hide-label>
        <div style="text-align: right;width: 100%;">
          <a-space style="justify-content: flex-end;">
            <a-button size="medium" @click="onOverClose" class="closeBtn">取消</a-button>
            <a-button size="medium" type="primary" html-type="submit" :loading="overLoading">确认</a-button>
          </a-space>
        </div>
      </a-form-item>  
    </a-form> 
  </a-modal>
</a-card>      
</template>


<script lang="ts">
export default {
  name: 'CluesIndex'
}

</script>

<script setup lang="ts">
import { makeBetweenString } from '@/utils/index'
import { ref , reactive, computed, onMounted } from 'vue'
import { isUndefined, isNull } from 'lodash';
import { Message } from '@arco-design/web-vue';
import { useRouter } from 'vue-router';
import { useDictStore, useCommonStore, useUserStore } from '@/store';
import { 
  getCluePageList, 
  cluesPhoneViewed, 
  updateCommProgress,
  clueHandedOver,
  getClueSlectList
 } from '@/api/clues'
 
import { getCurrentDate, getCurrentNextDayDate } from '@/utils/dateUtil';

import dayjs from 'dayjs';
const router = useRouter();
let starTime = getCurrentDate()
let endTime = getCurrentNextDayDate();

const crudTable = ref();
const dictStore = useDictStore();
const userStore = useUserStore();
const commonStore = useCommonStore();
let handOvderForm = ref();
let modalVisible = ref<boolean>(false)
let overLoading = ref<boolean>(false)

let handForm = reactive({
     id: '',
     uid: '',
     remark: ''
})

let adminSearchForm = [
    { 
      field: 'createTime', 
      span: 6,
      slots: {
        default: 'createTimeSlot'
      },
      defaultValue: [
        `${starTime}`,
        `${endTime}`
      ],
    },
    { 
      field: 'organization_personnel_uid',
      title: '跟进经理', 
      span: 3, 
      slots: {
        default: 'personnelSlot'
      } 
    },
    { 
      field: 'phone_viewed',
      title: '号码状态', 
      span: 3, 
      slots: {
        default: 'phoneViewedSlot'
      } 
    },
    { 
      field: 'plan',
      title: '沟通进度', 
      span: 3, 
      slots: {
        default: 'pushPlanSlot'
      } 
    },
    { 
      field: 'mobile', 
      title: '手机号', 
      span: 4, 
      slots: {
        default: 'mobileSearchSlot'
      } 
    }
];


let userSearchForm = [
    { 
      field: 'createTime', 
      span: 6,
      slots: {
        default: 'createTimeSlot'
      },
      defaultValue: [
        `${starTime}`,
        `${endTime}`
      ],
    },
    { 
      field: 'phone_viewed',
      title: '号码状态', 
      span: 3, 
      slots: {
        default: 'phoneViewedSlot'
      } 
    },
    { 
      field: 'plan',
      title: '沟通进度', 
      span: 3, 
      slots: {
        default: 'pushPlanSlot'
      } 
    },
    { 
      field: 'mobile', 
      title: '手机号', 
      span: 4, 
      slots: {
        default: 'mobileSearchSlot'
      } 
    }
];


let searchForm = ref(
  ['admin'].includes(userStore?.role) 
  ? adminSearchForm : userSearchForm
)

const columns = [
  {
    title: '用户姓名',
    dataIndex: 'name',
    align: 'center',
    width: 150,
    minWidth: 100,
  },
  {
    title: '年龄',
    dataIndex: 'age',
    align: 'center'
  },
  {
    title: '性别',
    align: 'center',
    dataIndex: 'gender',
    slotName: 'genderSlot'
  },
  {
    title: '手机号',
    width: 180,
    dataIndex: 'mobile',
    align: 'center',
    slotName: 'mobileSlot'
  },
  {
    title: '省份-城市',
    dataIndex: 'city',
    align: 'center',
    width: 200,
    slotName: 'entryStatusSlot'
  },
  {
    title: '申请额度',
    dataIndex: 'loan_money',
    align: 'center'
  },
  {
    title: '申请时间',
    align: 'center',
    width: 200,
    dataIndex: 'createtime',
    slotName: 'cellCreatetimeSlot'
  },

  {
    title: '芝麻分',
    align: 'center',
    dataIndex: 'sesame_score',
    slotName: 'sesameScoreSlot'
  },

  {
    title: '车产',
    align: 'center',
    dataIndex: 'car',
    slotName: 'cellCarSlot'
  },
  {
    title: '房产',
    align: 'center',
    dataIndex: 'house',
    slotName: 'cellHouseSlot'
  },
  {
    title: '公积金',
    align: 'center',
    dataIndex: 'accumulation_fund',
    slotName: 'accumulationFundSlot'
  },
  {
    title: '社保',
    align: 'center',
    dataIndex: 'social_security',
    slotName: 'socialSecuritySlot'
  },
  {
    title: '企业主',
    align: 'center',
    dataIndex: 'business_owner',
    slotName: 'businessOwnerSlot'
  },
  {
    title: '跟进经理',
    align: 'center',
    dataIndex: 'nickname',
  },
  {
    title: '沟通进度',
    align: 'center',
    slotName: 'cellPlanSlot'
  },
  {
    title: '跟进详情备注',
    align: 'center',
    dataIndex: 'remark',
  },
  {
    title: '用户详情',
    align: 'center',
    width: 150,
    fixed: 'right',
    slotName: 'userInfoSlot'
  },
  {
    title: '操作',
    align: 'center',
    fixed: 'right',
    width: 230,
    slotName: 'actionSlot'
  },
];

let phoneViewedList = ref([
    {
      label: '全部',
      value: 'all',  
    },
    {
      label: '显示',
      value: '1',  
    },
    {
      label: '隐藏',
      value: '0',  
    }
])

let compilationTime = (time: number)=>{
  return dayjs(time * 1000).format('YYYY-MM-DD HH:mm:ss')
}

let persionSlectList = ref([])
let selectItem = ref()
let itemNickname = ref();
const tableRowClick = (result: any)=>{
  selectItem.value = result;
  itemNickname.value = result?.nickname;
}

const fetchData = ({ page, size, query })=>{
   let start_time: string = '';
   let end_time: string = '';
   const { 
    createTime, plan, phone_viewed, mobile,
    organization_personnel_uid,
  } = query;
   if(!isUndefined(createTime) && !isNull(createTime)){
      let [startTime, endTime ] = createTime;
      start_time = String(dayjs(startTime).valueOf() / 1000);
      end_time = String(dayjs(endTime).valueOf() / 1000);
   }

   return getCluePageList({ 
      page, size, start_time, end_time,
      plan, phone_viewed, mobile,
      organization_personnel_uid
   })
}

const onHandedOver = (record: any)=>{
   if(record?.phone_viewed == 1){
    return Message.warning('不能移交！')
   }

   handForm.id = record.id;
   modalVisible.value = true;
}

const onOverClose = ()=>{
  handOvderForm.value.resetFields();
  overLoading.value = false;
  modalVisible.value = false;
}

const handleOverSubmit = async ({errors, values }) => {
    if (overLoading.value) return;
    if (!errors) {
      overLoading.value = true;
      await clueHandedOver(values).then(({ code }: any)=>{
        if(code === 1){
          onOverClose();
          Message.success('移交成功');
          crudTable.value.reloadEvent();
        }
      }).catch(()=>{
        overLoading.value = false;
      })
    }
}

const showPhone = (record : any) =>{
  cluesPhoneViewed(record?.id).then(({ data, code } : any)=>{
     if(code === 1){
        commonStore.addUserMobile({
          uid: record?.id,
          mobile: data?.mobile,
          // 过期时间为10分钟
          expired: dayjs().add(10, 'minute').valueOf(),
       });
       Message.success('获取成功');
       crudTable.value.reloadEvent();
     }
  })
}

const showUserMobile = (uid: number)=>{
  return commonStore.getUserMobileByUid(uid)
}

const cluePlanList = computed(()=>{
  return dictStore?.getProductCluePlan || {}
})

const cellShowCity = (code: string)=>{
   return dictStore.getCityNameByCode(code);
}

const cellPlanSlotConver = (plan: string)=>{
   return dictStore.getPlanTextByKey(plan);
}

const jumpToInfo = (uid: any)=>{
  router.push({ 
    path: '/clues/cluesUserInfo',
    query: { uid }
  })
}

const updatePlanPross = (record: any)=>{
  router.push({ 
    path: '/clues/cluesUserInfo',
    query: { uid: record?.id }
  })
}


const selectClueList = ()=> {
  /// 管理员才可以访问
  if(['admin'].includes(userStore?.role)){
    getClueSlectList().then(({ data }: any)=>{
      persionSlectList.value = data?.datalist || []
    });
  }
}

onMounted(()=>{
  selectClueList();
})

</script>

<style scoped lang='less'>
  .closeBtn{
    background: #FFFFFF;
    border: 1px solid #A7AFBF;
    color: #333333;
    font-weight: bold;
    font-size: 14px;
  }

  .cell-warning{
    font-weight: 400;
    font-size: 14px;
    color: #FA6A00;
  }

  .cell-default{
    font-weight: 400;
    font-size: 14px;
    color: #333333;
  }

  :deep(.arco-input-wrapper){
     .arco-input[disabled] {
        -webkit-text-fill-color: #333333;
     }
  }

</style>